<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
class GoodsController extends Controller
{
    //

    public function add()
    {
        $data = DB::table('category') 
        -> select('category.*',DB::raw("concat(category.path,',',category.id) as sortpath"))
        ->orderBy('sortpath')
        -> get();

          foreach ($data as $key => $value)
        {
            $num = substr_count($value -> path, ',');
            $str = str_repeat('|----', $num);
            $data[$key] ->name = $str.$value -> name;
        }

        return view('admin.goods.add', ['title' => '商品添加', 'data' => $data]);
    }


    public function insert(Request $request)
    {

        
        $this->validate($request,[
            'goodsname' => 'required',
            'goodspic' => 'required|image|max:2048',
            ],[
            'goodsname.required' => '商品名称不能为空',
            'goodspic.required' => '图片不能为空',
            'goodspic.image' => '上传的必须是一张图片',
            'goodspic_max.required' => '图片不能为空',
            'goodspic_max.image' => '上传的必须是一张图片',
            'goodspic.max' => '图片最大为2MB',
            ]);


        $data = $request -> except('_token');

        if($request -> hasFile('goodspic'))
        {
            if($request -> file('goodspic') -> isValid())
            {
                //处理商品图片
                $extension = $request -> file('goodspic') -> getClientOriginalExtension();

                $filename = mt_rand(10000000,99999999).'.'.$extension;
                $dir = './uploads/goodspic/';

                $request -> file('goodspic') -> move($dir, $filename);

                $data['goodspic'] = '/uploads/goodspic/'.$filename;
            }
        }else
        {
            return back() -> with(['info' => '添加失败']);
        }

        if($request -> hasFile('goodspic_max'))
        {
            if($request -> file('goodspic_max') -> isValid())
            {
                //处理详情大图
                $extension = $request -> file('goodspic_max') -> getClientOriginalExtension();

                $filename = mt_rand(10000000,99999999).'.'.$extension;
                $dir = './uploads/goodspic_max/';

                $request -> file('goodspic_max') -> move($dir, $filename);

                $data['goodspic_max'] = '/uploads/goodspic_max/'.$filename;
            }
        }else
        {
            return back() -> with(['info' => '添加失败']);
        }

        $time = Date('Y-m-d H:i:s');
        $data['scnt'] = 0;
        // $data['addtime'] = $time;
        $data['created_at'] = $time;
        $data['updated_at'] = $time;

        // dd($data);

        //添加数据
        // dd($data);

        $res = DB::table('goods') -> insert($data);

        if($res)
            {
                return redirect('/admin/goods/add') -> with(['info' => '添加成功']);
            }else
            {
                return back() -> with(['info' => '添加失败']);
            }
        
    }

    public function index(Request $request)
    {

        $num = $request -> input('num',10);
        $keywords = $request -> input('keywords','');

        $data = DB::table('goods as g1')
        -> select('g1.*','c1.name','c1.id')
        -> leftJoin('category as c1','g1.tid','=','c1.id')
        -> where('g1.goodsname','like','%'.$keywords.'%')
        -> paginate($num);
        // dd($data);
        // c pid = cname

        return view('admin.goods.index',['data' => $data, 'request' => $request -> all()]);
        // return view('admin.goods.index',['data' => $data]);
    }


    //修改
    public function edit($gid)
    {   
        $data_goods = DB::table('goods') -> where('gid',$gid) -> first();
        // dd($data_goods);
        $data_category = DB::table('category') -> get();
        
          foreach ($data_category as $key => $value)
        {
            $num = substr_count($value -> path, ',');
            $str = str_repeat('|----', $num);
            $data_category[$key] ->name = $str.$value -> name;
        }

        return view('admin.goods.edit',['data_category' => $data_category,'data_goods' => $data_goods]);
    }
    public function update(Request $request)
    {
        $this->validate($request,[
            'goodsname' => 'required',
            // 'goodspic' => 'required|image|max:2048',
            ],[
            'goodsname.required' => '商品名称不能为空',
            'store.required' => '库存不能为空',
            'status.required' => '请设置商品状态',
            // 'goodspic.required' => '图片不能为空',
            // 'goodspic.image' => '上传的必须是一张图片',
            // 'goodspic_max.required' => '详情不能为空',
            // 'goodspic_max.image' => '上传的必须是一张图片',
            // 'goodspic.max' => '图片最大为2MB',
            ]);

        $gid = $request -> gid;
        // dd($gid);
        $data = $request -> except('_token','id');
        // dd($data);
        if($request -> hasFile('goodspic'))
        {
             $this->validate($request,['goodspic.image' => '上传的必须是一张图片']);
            if($request -> file('goodspic') -> isValid())
            {
                //删除旧图片
                    $oldGoodspic = DB::table('goods') -> where('gid',$gid) -> first() -> goodspic;
                    if(!empty($oldGoodspic))
                    { 
                        if($oldGoodspic != '/uploads/goodspic/default.png')
                        {   
                            if(file_exists('.'.$oldGoodspic))
                            {
                                unlink('.'.$oldGoodspic);
                            }
                        }
                    }
                //处理商品图片
                $extension = $request -> file('goodspic') -> getClientOriginalExtension();
                $filename = mt_rand(10000000,99999999).'.'.$extension;
                $dir = './uploads/goodspic/';
                $request -> file('goodspic') -> move($dir, $filename);
                $data['goodspic'] = '/uploads/goodspic/'.$filename;
           } 
        }
        if($request -> hasFile('goodspic_max'))
        {   
            $this->validate($request,['goodspic.image' => '上传的必须是一张图片']);
            if($request -> file('goodspic_max') -> isValid())
            {
             //删除旧图片
                    $oldGoodspic_max = DB::table('goods') -> where('gid',$gid) -> first() -> goodspic_max;
                    if(!empty($oldGoodspic_max))
                    { 
                        if($oldGoodspic_max != '/uploads/goodspic_max/default.png')
                        {   
                            if(file_exists('.'.$oldGoodspic_max))
                            {
                                unlink('.'.$oldGoodspic_max);
                            }
                        }
                    }
                //处理详情大图
                $extension = $request -> file('goodspic_max') -> getClientOriginalExtension();

                $filename = mt_rand(10000000,99999999).'.'.$extension;
                $dir = './uploads/goodspic_max/';

                $request -> file('goodspic_max') -> move($dir, $filename);

                $data['goodspic_max'] = '/uploads/goodspic_max/'.$filename;
            }
        }
        $time = Date('Y-m-d H:i:s');
        $data['updated_at'] = $time;
        $res = DB::table('goods') -> update($data);
        if($res)
            {
                return redirect('/admin/goods/index') -> with(['info' => '修改成功']);
            }else
            {
                return back() -> with(['info' => '修改失败']);
            }
    }
    public function delete($gid)
    {
        
        $oldGoodspic = DB::table('goods') -> where('gid',$gid) -> first() -> goodspic;
        $oldGoodspic_max = DB::table('goods') -> where('gid',$gid) -> first() -> goodspic_max;
        $res = DB::table('goods') -> where('gid', $gid) -> delete();
        if(!empty($oldGoodspic))
        { 
            if($oldGoodspic != '/uploads/goodspic/default.png')
            {   
                if(file_exists('.'.$oldGoodspic))
                {
                    unlink('.'.$oldGoodspic);
                }
            }
        }
         if(!empty($oldGoodspic_max))
        { 
            if($oldGoodspic_max != '/uploads/goodspic_max/default.png')
            {   
                if(file_exists('.'.$oldGoodspic_max))
                {
                    unlink('.'.$oldGoodspic_max);
                }
            }
        }
        // dd($res);
        if($res)
        {
            return redirect('/admin/goods/index') -> with(['info' => '删除成功']);
        }else
        {
            return back() -> with(['info' => '删除失败']);
        }
    }
}
